var util = require('../../utils/util.js'); //导入实现时间获取
var app = getApp();
const db = wx.cloud.database({
  throwOnNotFound: false
})
const _ = db.command

Page({
  data: {
    active: 0,
    re: false,
    price1: 0,
    price2: 0,
    type: "",
    content: "",
    time: "",
    nowMoney: 0,
    goodsList: [],
    serveList: [],
    userInfo: [],
    detail: []
  },
  onLoad: function (options) {


    wx.cloud.callFunction({
        name: "queryGoodsList",
        success: res => {
          console.log("查询物品成功", res)
          this.setData({
            goodsList: res.result.data,

          })
        }
      }),

      wx.cloud.callFunction({
        name: "queryServeList",
        success: res => {
          console.log("查询服务成功", res)
          this.setData({
            serveList: res.result.data,

          })
        }
      }),


      //判断用户是否授权登录
      wx.getSetting({
        success: function (res) {
          if (res.authSetting['scope.userInfo']) {
            console.log("用户已授权")
          } else {
            console.log("用户未授权")
            wx.redirectTo({
              url: '../mine/login'
            });
          }
        }
      });

    //判断用户是否注册，返回re值true/false
    wx.cloud.callFunction({ //调用云函数获取openid
      name: "getOpenId",
      complete: res => {
        db.collection("userInfo").where({
          _openid: res.result.openid //进行筛选
        }).get({
          success: res => {
            console.log("查找用户注册信息成功", res)
            if (res.data.length === 1) {
              this.setData({
                  re: true,
                  userInfo: res.data[0]
                }),
                console.log("用户已注册", this.data.re)
            } else {
              this.setData({
                  re: false
                }),
                console.log("用户未注册", this.data.re)

            }
          },
          fail: res => {
            console.log("查找用户注册信息失败", res)
          }
        })
      }
    });


  },

  //页面切换
  onChange(event) {
    wx.showToast({
      title: `切换到标签 ${event.detail.name}`,
      icon: 'none'
    });
  },

  //礼物兑换按钮确认
  GoodsExchange: function (e) {


    const id = e.currentTarget.id;
    let that = this;
    let re = this.data.re;
    let price1 = this.data.price1;

    console.log("re:", re)

    console.log("商品id是:", id)
    //先判断是否注册
    if (re == false) {
      console.log("用户未注册", this.data.re)
      this.setData({
          re: false
        }),
        wx.showModal({
          title: '提示',
          content: '请先注册成为志愿者！',
          success(res) {
            if (res.confirm) {
              console.log('用户点击确定'),
                wx.navigateTo({
                  url: '../register/newuser',
                })
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })

    } else {


      //判断用户时间货币是否足够
      db.collection("goods-List").doc(id).get({
        success: (res) => {
          console.log(res)
          this.setData({
            detail: res.data,
            price1: res.data.price,
            content: res.data.title,
            type: "兑换物品",
            time: util.formatTime(new Date())

          })
          console.log("price1为：", this.data.price1)

          wx.cloud.callFunction({
            name: "getOpenId",
            complete: res => {
              db.collection("userInfo").where({
                _openid: res.result.openid
              }).get({
                success: res => {
                  console.log("该用户的_id为：", res)
                  console.log("该用户的时间货币为：", res.data[0].timecurrency)

                  this.setData({
                    nowMoney: res.data[0].timecurrency - this.data.price1
                  })
                  if (res.data[0].timecurrency < this.data.price1) {
                    wx.showToast({
                      title: '时间货币不足',
                    })

                    console.log("时间货币不足")

                  } else {
                    //时间货币足够的情况下,判断物品余额是否>0
                    //判断剩余量是否>0

                    db.collection("goods-List").doc(id).field({
                      num: true
                    }).get({
                      success: (res) => {
                        console.log(res)
                        if (res.data.num > 0) {
                          console.log("num>0，允许兑换", res.data.num)

                          console.log("弹出兑换确认框")
                          wx.showModal({
                            title: '兑换确认',
                            content: '您确认兑换吗',
                            success: (res) => {
                              if (res.confirm) {
                                console.log('用户点击确定')
                                wx.showToast({
                                    title: '兑换成功！',
                                    icon: '', //默认值是success,就算没有icon这个值，就算有其他值最终也显示success
                                    duration: 1200, //停留时间
                                  }),
                                  //goods-List数据库更新num-1
                                  db.collection('goods-List').doc(id).update({
                                    data: {
                                      num: _.inc(-1)
                                    },
                                    success: (res) => {

                                      console.log("兑换成功，num-1", res)
                                      //更新数组,使得页面num更新
                                      wx.cloud.callFunction({
                                        name: "queryGoodsList",
                                        success: res => {
                                          console.log("查询物品成功", res)
                                          this.setData({
                                            goodsList: res.result.data

                                          })
                                        }
                                      });

                                      //查找用户的_id，通过id更新待审核兑换数据,userInfo的auditexchange+1,时间货币相应的减少.增加history明细记录
                                      wx.cloud.callFunction({ //调用云函数获取openid
                                        name: "getOpenId",
                                        complete: res => {
                                          db.collection("userInfo").where({
                                            _openid: res.result.openid //进行筛选
                                          }).get({

                                            success: res => {
                                              console.log("该用户的_id为：", res.data[0]._id)
                                              db.collection('userInfo').doc(res.data[0]._id).update({
                                                data: {
                                                  auditexchange: _.inc(+1),
                                                  timecurrency: _.inc(-this.data.price1)
                                                }
                                              })
                                              console.log("更新成功，待审核兑换+1,时间货币减少")

                                              //增加该用户明细记录
                                              db.collection("history").add({
                                                data: {
                                                  content: this.data.content,
                                                  price: this.data.price1,
                                                  type: this.data.type,
                                                  time: this.data.time,
                                                  nowMoney: this.data.nowMoney
                                                },
                                                success: res => {
                                                  console.log("明细记录添加成功", res)
                                                }

                                              })


                                              //增加该用户兑换记录 status表示状态，0：待审核，1：通过，2：未通过
                                              db.collection("myExchangeList").add({
                                                data: {
                                                  realName: this.data.userInfo.realName,
                                                  userID: this.data.userInfo.userID,
                                                  title: this.data.detail.title,
                                                  desc: this.data.detail.desc,
                                                  time: this.data.time,
                                                  price: this.data.detail.price,
                                                  imgList: this.data.detail.imgList,
                                                  status: 0
                                                },
                                                success: res => {
                                                  console.log("物品兑换记录添加成功", res)
                                                }

                                              })
                                            },
                                            fail: res => {
                                              console.log("获取用户_id信息失败", res)
                                            }
                                          })
                                        }
                                      });

                                    },
                                    fail: function (res) {
                                      console.log("更新num失败", res)

                                    }
                                  })
                              } else if (res.cancel) {
                                console.log('用户点击取消')
                              }
                            }
                          })

                        } else {
                          wx.showToast({
                            title: '抱歉兑换已结束',
                          })
                        }
                      }
                    })


                  }
                },
                fail: res => {
                  console.log("获取用户_id信息失败", res)
                }
              })
            }
          });


        }
      })






    }
  },

  //服务兑换按钮确认
  ServeExchange: function (e) {
    const id = e.currentTarget.id;
    let that = this;
    let re = this.data.re;
    let price2 = this.data.price2;
    let serveList = this.data.serveList;
    console.log("re:", re)
    console.log("goodslist:", serveList)
    console.log("商品id是:", id)
    //先判断是否注册
    if (re == false) {
      console.log("用户未注册", this.data.re)
      this.setData({
          re: false
        }),
        wx.showModal({
          title: '提示',
          content: '请先注册成为志愿者！',
          success(res) {
            if (res.confirm) {
              console.log('用户点击确定'),
                wx.navigateTo({
                  url: '../register/newuser',
                })
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })

    } else {

      //判断用户时间货币是否足够
      db.collection("serveList").doc(id).get({
        success: (res) => {
          console.log(res)
          this.setData({
            detail: res.data,
            price2: res.data.price,
            content: res.data.title,
            type: "兑换服务",
            time: util.formatTime(new Date())
          })
          console.log("price2为：", this.data.price2)

          wx.cloud.callFunction({
            name: "getOpenId",
            complete: res => {
              db.collection("userInfo").where({
                _openid: res.result.openid
              }).get({
                success: res => {
                  console.log("该用户的_id为：", res)
                  console.log("该用户的时间货币为：", res.data[0].timecurrency)
                  this.setData({
                    nowMoney: res.data[0].timecurrency - this.data.price2
                  })
                  if (res.data[0].timecurrency < this.data.price2) {
                    wx.showToast({
                      title: '时间货币不足',
                    })

                    console.log("时间货币不足")

                  } else {
                    //时间货币足够的情况下,判断物品余额是否>0
                    //判断剩余量是否>0

                    db.collection("serveList").doc(id).field({
                      num: true
                    }).get({
                      success: (res) => {
                        console.log(res)
                        if (res.data.num > 0) {
                          console.log("num>0，允许兑换", res.data.num)

                          console.log("弹出兑换确认框")
                          wx.showModal({
                            title: '兑换确认',
                            content: '您确认兑换吗',
                            success: (res) => {
                              if (res.confirm) {
                                console.log('用户点击确定')
                                wx.showToast({
                                    title: '兑换成功！',
                                    icon: '', //默认值是success,就算没有icon这个值，就算有其他值最终也显示success
                                    duration: 1200, //停留时间
                                  }),
                                  //serveList数据库更新num-1
                                  db.collection('serveList').doc(id).update({
                                    data: {
                                      num: _.inc(-1)
                                    },
                                    success: (res) => {

                                      console.log("兑换成功，num-1", res)
                                      //更新数组,使得页面num更新
                                      wx.cloud.callFunction({
                                        name: "queryServeList",
                                        success: res => {
                                          console.log("查询服务成功", res)
                                          this.setData({
                                            serveList: res.result.data

                                          })
                                        }
                                      });

                                      //查找用户的_id，通过id更新待审核兑换数据,userInfo的auditexchange+1,时间货币相应的减少
                                      wx.cloud.callFunction({ //调用云函数获取openid
                                        name: "getOpenId",
                                        complete: res => {
                                          db.collection("userInfo").where({
                                            _openid: res.result.openid //进行筛选
                                          }).get({

                                            success: res => {
                                              console.log("该用户的_id为：", res.data[0]._id)
                                              db.collection('userInfo').doc(res.data[0]._id).update({
                                                data: {
                                                  auditexchange: _.inc(+1),
                                                  timecurrency: _.inc(-this.data.price2)
                                                }
                                              })
                                              console.log("更新成功，待审核兑换+1,时间货币减少")


                                              //增加该用户明细记录
                                              db.collection("history").add({
                                                data: {
                                                  content: this.data.content,
                                                  price: this.data.price2,
                                                  type: this.data.type,
                                                  time: this.data.time,
                                                  nowMoney: this.data.nowMoney
                                                },
                                                success: res => {
                                                  console.log("明细记录添加成功", res)
                                                }

                                              });


                                              //增加该用户兑换记录 status表示状态，0：待审核，1：通过，2：未通过
                                              db.collection("myExchangeList").add({
                                                data: {
                                                  realName: this.data.userInfo.realName,
                                                  userID: this.data.userInfo.userID,
                                                  title: this.data.detail.title,
                                                  desc: this.data.detail.desc,
                                                  time: this.data.time,
                                                  price: this.data.detail.price,
                                                  imgList: this.data.detail.imgList,
                                                  status: 0
                                                },
                                                success: res => {
                                                  console.log("服务兑换记录添加成功", res)
                                                }

                                              });

                                            },
                                            fail: res => {
                                              console.log("获取用户_id信息失败", res)
                                            }
                                          })
                                        }
                                      });

                                    },
                                    fail: function (res) {
                                      console.log("更新num失败", res)

                                    }
                                  })
                              } else if (res.cancel) {
                                console.log('用户点击取消')
                              }
                            }
                          })

                        } else {
                          wx.showToast({
                            title: '抱歉兑换已结束',
                          })
                        }
                      }
                    })


                  }
                },
                fail: res => {
                  console.log("获取用户_id信息失败", res)
                }
              })
            }
          });


        }
      })






    }
  }

});